package define

import (
	"fmt"
	"github.com/jlaffaye/ftp"
	"github.com/up-zero/gotool/fileutil"
	"os"
	"path/filepath"
	"time"
)

var AppName = "light-ftp"

func GetConfigPath() (string, error) {
	p, err := os.UserConfigDir()
	if err != nil {
		return "", err
	}

	return filepath.Join(p, AppName, "config.json"), nil
}

func (in *SysConfig) Read() error {
	p, err := GetConfigPath()
	if err != nil {
		return err
	}
	fileutil.FileRead(p, in)
	return nil
}

func (in *SysConfig) Save() error {
	p, err := GetConfigPath()
	if err != nil {
		return err
	}
	return fileutil.FileSave(p, in)
}

// NewClient 初始化 FTP 客户端
func NewClient(site SiteConfig) (*FtpClient, error) {
	addr := fmt.Sprintf("%s:%s", site.Host, site.Port)
	conn, err := ftp.Dial(addr, ftp.DialWithTimeout(time.Second*10))
	if err != nil {
		return nil, err
	}
	if err = conn.Login(site.Account, site.Password); err != nil {
		return nil, err
	}
	return &FtpClient{
		Conn: conn,
	}, nil
}

func HumanSize(size uint64) string {
	const (
		B  = 1
		KB = 1024 * B
		MB = 1024 * KB
		GB = 1024 * MB
	)
	switch {
	case size >= GB:
		return fmt.Sprintf("%.2f GB", float64(size)/GB)
	case size >= MB:
		return fmt.Sprintf("%.2f MB", float64(size)/MB)
	case size >= KB:
		return fmt.Sprintf("%.2f KB", float64(size)/KB)
	default:
		return fmt.Sprintf("%d B", size)
	}
}
